﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Mvc4.Filters;
using Mvc4.Models;
using System.Configuration;
using DataAccess.Datatypes;
using BussinesLayer.Services;
using WebMatrix.WebData;

namespace Mvc4.Controllers
{
    public class PayController : Controller
    {
        private GoodServices gs = new GoodServices();

        [Authorize]
        [InitializeSimpleMembership]
        public ActionResult Pay(int goodId, string siteName, DateTime? from = null, DateTime? to = null)
        {
            if (from.HasValue && to.HasValue)
            {
                Good good = gs.RentGood(WebSecurity.CurrentUserId, goodId, from ?? DateTime.Now, to ?? DateTime.Now);
                if (good != null)
                {
                    Paypal paypal = new Paypal();
                    paypal.cmd = "_xclick";
                    paypal.business = ConfigurationManager.AppSettings["BussinessAccountKey"];
                    ViewBag.actionURL = "https://www.sandbox.paypal.com/cgi-bin/websrc";
                    paypal.currency_code = ConfigurationManager.AppSettings["CurrencyCode"];

                    paypal.cancel_return = ConfigurationManager.AppSettings["Ol4RentUrl"] + siteName;
                    paypal.@return = ConfigurationManager.AppSettings["Ol4RentUrl"] + siteName + "/View/" + goodId.ToString();
                    paypal.notify_url = ConfigurationManager.AppSettings["Ol4RentUrl"] + "pay/acceptedpay?token=" + good.Url;

                    paypal.item_name = good.Name;
                    paypal.amount = good.PriceDay.ToString().Replace(',', '.');
                    return View(paypal);
                }
            }

            return RedirectToAction("View", siteName, new { id = goodId, error = "rent"} );
        }

        public Action AcceptedPay(string token)
        {
            gs.RentConfirmation(token);
            return null;
        }

    }
}